import { defineStore } from "pinia";
import { ref } from "vue";
import store from "@/store";
import { loginApi } from "@api/auth";
import { LoginRequestDatas } from "@api/auth/types";
import cacheUtils from "@/utils/cacheUtils";

export const useUserStore = defineStore("user", () => {
  const token = ref<string>(cacheUtils.get("lang") || "");
  // const username = ref<string>("");
  // const nickname = ref<string>("");
  /** 登录 */
  const login = async ({ username, password }: LoginRequestDatas) => {
    const { data } = await loginApi({ username, password });
    console.log(data);
    cacheUtils.set("userToken", data.token);
    token.value = data.token;
  };
  /** 重置 Token */
  const removeToken = () => {
    cacheUtils.remove("data");
  };
  /** 登出 */
  const logout = () => {
    removeToken();
    token.value = "";
  };

  return {
    token,
    login,
    logout,
  };
});

export function useUserStoreHook() {
  return useUserStore(store);
}
